package com.kosinsut.youtubeplaylistbuilder.songretriever;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import com.kosinsut.youtubeplaylistbuilder.Song;

/**
 * Example SongRetriever which will browse the billboard and get the list of top-100 songs
 * @author Kosin
 *
 */
public class BillBoardSongRetriever implements SongRetriever {

	private static final String WEB_URL = "http://www.billboard.com/rss/charts/hot-100";
	
	@Override
	public List<Song> retrieveSongs() throws SongRetrieverException {
		WebClient webClient = new WebClient();
		List<Song> songList = new ArrayList<Song>();
		try {
			XmlPage page = webClient.getPage(WEB_URL);
			NodeList titleList = page.getXmlDocument().getElementsByTagName("title");
			int totalSongs = titleList.getLength();
			for (int i=1; i<totalSongs; i++) {
				Node title = titleList.item(i);
				String titleText = title.getTextContent();
				String[] songDetail = titleText.split(":", 2)[1].split(",", 2);
				songList.add(new Song(songDetail[0], songDetail[1]));
			}
		} catch (FailingHttpStatusCodeException e) {
			
			e.printStackTrace();
		} catch (MalformedURLException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		webClient.closeAllWindows();
		return songList;
	}

}
